package org.goldenmock.web.server;

import com.google.common.io.CharStreams;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;

/**
 * Functionally equivalent to HttpServletRequest, but with the contentstream already
 * converted into a string. This is necessary when multiple content matchers need to
 * evaluate the request, since a stream can only be consumed once.
 *
 * @author Robin Wagenaar
 * @author Arjen van Staalduinen
 */
public class EasyHttpRequest extends HttpServletRequestWrapper {

    private String content;

    public EasyHttpRequest(HttpServletRequest request) {
        super(request);
        try {
            if(request.getReader() != null && request.getReader().ready()){
                content = CharStreams.toString(request.getReader());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public String getContentAsString() {
        return content;
    }

    @Override
    public String toString() {
        return "EasyHttpRequest [ method=" + getMethod() + ", requestURL=" + getRequestURL() + " content=" + getContentAsString() + "]";
    }
}
